package com.example.cpoopc.listview_test;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

/**
 * Created by cpoopc on 2015/1/26.
 */
public class MyRelativeLayout extends RelativeLayout{
    private int mHeadHeight = 400;

    public MyRelativeLayout(Context context) {
        super(context);
    }

    public MyRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if(overHead()){
            return true;
        }
        return super.onInterceptTouchEvent(ev);
    }

    private boolean overHead() {
        int[] location = new int[2];
        getLocationInWindow(location);
        if(location[1]<=mHeadHeight){
            return true;
        }
        return false;
    }

    private float positionX;
    private float positionY;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                positionX = event.getX();
                positionY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                float shiftY = event.getY() - positionY;
                moveY(event.getY(),shiftY);
                break;
            case MotionEvent.ACTION_UP:
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    private void moveY(float position_y, float shiftY) {
        float y = position_y + shiftY;
        if(mHeadHeight - y <= 0){
            scrollTo(0, -mHeadHeight);
        }else{
            scrollTo(0, (int) y);
        }
    }
}
